//pages/index/index
<template>
  <view class="wiki-app">
    <!-- 浮动菜单按钮（仅在侧边栏关闭时显示） -->
    <view 
      class="float-menu" 
      @click="openMenu"
      v-if="!isMenuOpen"
    >
      <view class="menu-icon">
        <view class="menu-line"></view>
        <view class="menu-line"></view>
        <view class="menu-line"></view>
      </view>
    </view>

    <!-- 遮罩层（点击关闭侧边栏） -->
    <view 
      v-if="isMenuOpen" 
      class="sidebar-mask" 
      @click="closeMenu"
      :class="{ 'mask-active': isMenuOpen }"
    ></view>

    <!-- 侧边栏 -->
    <WikiSidebar
      :isOpen="isMenuOpen"
      :currentPath="currentPath"
      :treeData="structuredTreeData"
      :listData="listData"
      :selectedItem="selectedListData"
      @navigate="navigateToDirectory"
      @go-home="goToHome"
      @go-back="goBack"
      @close="closeMenu"
    />

    <!-- 内容区域 -->
    <WikiContent
      ref="wikiContent"
      :selectedListData="selectedListData"
      :selectedSingleData="selectedSingleData"
      :isLoading="isLoading"
    />
    
    <!-- 页脚 -->
    <Footer class="app-footer" />
  </view>
</template>

<script>
import Footer from '../components/Footer.vue';
import WikiSidebar from '../components/WikiSidebar.vue';
import WikiContent from '../components/WikiContent.vue';
import { fetchWikiData, fetchSingleContent } from '../utils/wikiApi';
import { buildStructuredTreeData, findItemByPath } from '../utils/treeUtils';
import uniIcons from '../../node_modules/@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'

export default {
  components: {
    uniIcons,
    Footer,
    WikiSidebar,
    WikiContent
  },
  data() {
    return {
      isMenuOpen: false,
      treeData: [],
      listData: [],
      structuredTreeData: [],
      currentPath: '',
      selectedListData: null,
      selectedSingleData: null,
      isLoading: false,
      isInitialized: false
    };
  },
  computed: {
    currentPathDisplay() {
      return this.currentPath === '' ? '根目录' : 
             this.currentPath === 'home' ? '主页' : 
             `当前路径: ${this.currentPath}`;
    }
  },
  methods: {
    // 打开菜单（按钮点击后消失）
    openMenu() {
      this.isMenuOpen = true;
    },

    // 关闭菜单（仅通过遮罩层触发）
    closeMenu() {
      this.isMenuOpen = false;
    },

    async navigateToDirectory(item) {
      if (this.isLeafNode(item)) {
        this.selectedListData = item;
        await this.fetchContent(item.id);
      } else {
        this.currentPath = item.path;
        this.selectedListData = null;
        this.selectedSingleData = null;
      }
    },
    
    isLeafNode(item) {
      return !item.isFolder || 
             (item.children && item.children.length === 0) ||
             (!item.children && this.listData.some(listItem => listItem.path === item.path));
    },
    
    async fetchContent(id) {
      this.isLoading = true;
      this.selectedSingleData = null;
      try {
        this.selectedSingleData = await fetchSingleContent(id);
        uni.setNavigationBarTitle({
          title: this.selectedListData.title
        });
      } catch (err) {
        console.error('查询失败:', err);
        uni.showToast({
          title: '内容加载失败',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
      }
    },
    
    goToHome() {
      const homeItem = this.listData.find(item => item.path === 'home') || 
                      this.treeData.find(item => item.path === 'home');
      if (homeItem) {
        this.currentPath = '';
        this.selectedListData = homeItem;
        if (this.isLeafNode(homeItem)) {
          this.fetchContent(homeItem.id);
        }
      }
    },
    
    goBack() {
      if (!this.currentPath) return;
      
      const pathParts = this.currentPath.split('/');
      pathParts.pop();
      this.currentPath = pathParts.join('/');
      
      if (!this.currentPath) return;
      
      const currentItem = findItemByPath(this.structuredTreeData, this.currentPath);
      if (currentItem) {
        this.selectedListData = currentItem;
        if (this.isLeafNode(currentItem)) {
          this.fetchContent(currentItem.id);
        }
      }
    },
    
    // 搜索跳转处理 - 统一处理所有搜索跳转方案
    handleSearchJump() {
      try {
        // 方案1：检查新的存储键名（来自搜索页面的 navigateBackWithData）
        const searchResult = uni.getStorageSync('search_target_path');
        if (searchResult && searchResult.path) {
          console.log('发现搜索跳转请求(search_target_path):', searchResult.path, searchResult.title);
          uni.removeStorageSync('search_target_path');
          this.handlePathParam(searchResult.path);
          uni.showToast({
            title: `已跳转到: ${searchResult.title || '目标页面'}`,
            icon: 'success',
            duration: 1500
          });
          return;
        }
        
        // 方案2：检查备用存储键名（来自搜索页面的 useStorageFallback）
        const jumpPath = uni.getStorageSync('search_jump_path');
        const jumpTitle = uni.getStorageSync('search_jump_title');
        if (jumpPath) {
          console.log('发现搜索跳转请求(search_jump_path):', jumpPath, jumpTitle);
          uni.removeStorageSync('search_jump_path');
          uni.removeStorageSync('search_jump_title');
          this.handlePathParam(jumpPath);
          if (jumpTitle) {
            uni.showToast({
              title: `已跳转到: ${jumpTitle}`,
              icon: 'success',
              duration: 1500
            });
          }
          return;
        }
        
        // 方案3：检查旧的存储键名（兼容之前的代码）
        const oldSearchResult = uni.getStorageSync('last_search_result');
        if (oldSearchResult && oldSearchResult.path) {
          console.log('发现搜索跳转请求(last_search_result):', oldSearchResult.path);
          uni.removeStorageSync('last_search_result');
          this.handlePathParam(oldSearchResult.path);
          return;
        }
        
        console.log('未发现搜索跳转请求');
      } catch (e) {
        console.error('处理搜索跳转失败:', e);
      }
    },
    
    async handlePathParam(path) {
      try {
        console.log('开始处理路径:', path);
        
        if (!this.isInitialized) {
          console.log('等待数据初始化...');
          await this.waitForInitialization();
        }
        
        const decodedPath = decodeURIComponent(path);
        console.log('解码后路径:', decodedPath);
        
        // 1. 检查列表数据中的精确匹配
        const listItem = this.listData.find(item => item && item.path === decodedPath);
        if (listItem) {
          console.log('找到列表匹配:', listItem.title);
          this.currentPath = this.getParentPath(decodedPath);
          this.selectedListData = listItem;
          await this.fetchContent(listItem.id);
          return;
        }
        
        // 2. 检查树结构中的匹配
        const treeItem = findItemByPath(this.structuredTreeData, decodedPath);
        if (treeItem) {
          console.log('找到树结构匹配:', treeItem.title);
          this.currentPath = treeItem.isFolder ? treeItem.path : this.getParentPath(treeItem.path);
          if (this.isLeafNode(treeItem)) {
            this.selectedListData = treeItem;
            await this.fetchContent(treeItem.id);
          }
          return;
        }
        
        // 3. 尝试模糊匹配
        const similarItem = this.findSimilarPath(decodedPath);
        if (similarItem) {
          console.log('找到模糊匹配:', similarItem.title);
          this.currentPath = similarItem.isFolder ? similarItem.path : this.getParentPath(similarItem.path);
          if (this.isLeafNode(similarItem)) {
            this.selectedListData = similarItem;
            await this.fetchContent(similarItem.id);
          }
          return;
        }
        
        // 4. 默认回退到首页
        console.warn('未找到匹配的路径:', decodedPath);
        this.goToHome();
        uni.showToast({
          title: '未找到指定内容，已回到首页',
          icon: 'none'
        });
      } catch (error) {
        console.error('处理路径参数失败:', error);
        this.goToHome();
      }
    },
    
    waitForInitialization() {
      return new Promise((resolve) => {
        const checkInterval = setInterval(() => {
          if (this.isInitialized) {
            clearInterval(checkInterval);
            resolve();
          }
        }, 100);
        
        setTimeout(() => {
          clearInterval(checkInterval);
          console.warn('初始化等待超时，强制继续');
          resolve();
        }, 5000);
      });
    },
    
    getParentPath(path) {
      const parts = path.split('/');
      parts.pop();
      return parts.join('/');
    },
    
    findSimilarPath(path) {
      const normalizedPath = path.toLowerCase().trim();
      
      // 先检查列表数据
      const listMatch = this.listData.find(item => 
        item.path.toLowerCase().includes(normalizedPath) || 
        normalizedPath.includes(item.path.toLowerCase())
      );
      if (listMatch) return listMatch;
      
      // 检查树数据
      for (const item of this.structuredTreeData) {
        const found = this.searchTreeForPath(item, normalizedPath);
        if (found) return found;
      }
      
      return null;
    },
    
    searchTreeForPath(node, targetPath) {
      if (node.path.toLowerCase().includes(targetPath) || 
          targetPath.includes(node.path.toLowerCase())) {
        return node;
      }
      
      if (node.children) {
        for (const child of node.children) {
          const found = this.searchTreeForPath(child, targetPath);
          if (found) return found;
        }
      }
      
      return null;
    }
  },
  async mounted() {
    try {
      const { treeData, listData } = await fetchWikiData();
      this.treeData = treeData;
      this.listData = listData;
      this.structuredTreeData = buildStructuredTreeData(treeData, listData);
      this.isInitialized = true;
      
      // 检查是否有初始路径参数
      const pages = getCurrentPages();
      if (pages.length > 0) {
        const options = pages[pages.length - 1].options;
        if (options.path) {
          await this.handlePathParam(options.path);
          return;
        }
      }
      this.goToHome();
    } catch (error) {
      console.error('初始化数据失败:', error);
      uni.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    }
  },
  onShow() {
    console.log('首页显示，检查搜索跳转');
    this.handleSearchJump();
  },
  onLoad(options) {
    console.log('首页加载，参数:', options);
    
    // 处理 URL 参数
    if (options.path) {
      this.handlePathParam(options.path);
    }
    
    // 也检查存储的跳转
    this.handleSearchJump();
  },
  // 修复重复的分享方法，只保留一个
  onShareAppMessage() {
    if (this.selectedListData) {
      return {
        title: this.selectedListData.title,
        path: `/pages/index/index?path=${encodeURIComponent(this.selectedListData.path)}`,
        imageUrl: '/static/logo.png'
      };
    }
    return {
      title: '知识库管理系统',
      path: '/pages/index/index'
    };
  },
  
  onShareTimeline() {
    if (this.selectedListData) {
      return {
        title: this.selectedListData.title,
        query: `path=${encodeURIComponent(this.selectedListData.path)}`,
        imageUrl: '/static/logo.png'
      };
    }
    return {
      title: '知识库管理系统',
      query: ''
    };
  }
};
</script>

<style lang="scss">
.wiki-app {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  position: relative;
}

.float-menu {
  position: fixed;
  bottom: 30px;
  left: 20px;
  z-index: 1001;
  transition: opacity 0.3s ease;
  
  .menu-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: linear-gradient(135deg, #68684e 0%, #8b462a 100%);
    box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    
    .menu-line {
      width: 20px;
      height: 2px;
      background-color: #fff;
      margin: 3px 0;
    }
  }
}

.sidebar-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
  
  &.mask-active {
    opacity: 1;
    pointer-events: auto;
  }
}

.app-footer {
  margin-top: auto;
}
</style>